﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;

 
[ExecuteInEditMode]

public class EnvomentGlobalSetting : MonoBehaviour
{
    //public Camera MainCamera;
    [Label("主光源改点光源")]
    public Transform mainPointLight;

    [Label("风的方向")]
    public Vector2 windDir = new Vector2(0.01f, 0.0f);
    [Label("风强度")]
    [Range(0, 1f)]
    public float windPower = 1f;
    private ComputeBuffer constantBuffer;
    public static int m_ConstantBufferID = Shader.PropertyToID("LchGlobalParams");
    public struct GlobalData
    {

        public Vector4 lchMainLightParams;
        public Vector4 windParams;


    }

    static GlobalData[] bufferDatas = new GlobalData[1];
    void InitBuffer()
    {
        // 创建 Constant Buffer
        //这里4字节对齐，只用四字节的参数
        if (null == constantBuffer)
            constantBuffer = new ComputeBuffer(1, sizeof(float) * 4 * 2, ComputeBufferType.Constant);

    }
    void Start()
    {
        InitBuffer();
        UpdateBuffer();
    }

    private void OnEnable()
    {
        // 订阅相机开始渲染的事件
        //RenderPipelineManager.beginCameraRendering += OnBeginCameraRendering;
    }

    private void OnDisable()
    {
        // 取消订阅事件，避免内存泄漏
        //RenderPipelineManager.beginCameraRendering -= OnBeginCameraRendering;

        clearRenderState();
        // 释放 Buffer
        if (constantBuffer != null)
        {
            constantBuffer.Release();
            constantBuffer = null;
        }
    }

    void clearRenderState()
    {
        InitBuffer();
        bufferDatas[0].lchMainLightParams = new Vector4(0f, 0f, 0f, 0.0f);
        // 将数据写入 Buffer
        constantBuffer.SetData(bufferDatas);
        // 绑定到 Shader
        Shader.SetGlobalConstantBuffer(m_ConstantBufferID, constantBuffer, 0, constantBuffer.stride);
    }
    void UpdateBuffer()
    {
        InitBuffer();
  
       
        bufferDatas[0].windParams = new Vector4(windDir.x, 100, windDir.y, windPower);
        if (mainPointLight)
        {
            var pos = mainPointLight.position;
            bufferDatas[0].lchMainLightParams = new Vector4(pos.x, pos.y, pos.z, 1.0f);
        }
        else
        {
            bufferDatas[0].lchMainLightParams = new Vector4(0f, 0f, 0f, 0.0f);
        }
        // 将数据写入 Buffer
        constantBuffer.SetData(bufferDatas);
        // 绑定到 Shader
        Shader.SetGlobalConstantBuffer(m_ConstantBufferID, constantBuffer, 0, constantBuffer.stride);
    }
    /*private void OnBeginCameraRendering(ScriptableRenderContext context, Camera camera)
    {
        UpdateBuffer();
    }*/
//#if UNITY_EDITOR
    void Update()
    {
        /*if (!Application.isPlaying)
        {
           
        }*/
        UpdateBuffer();
    }

//#endif
}
     
